const userService = require('../../../services/userService');
const jwt = require('jsonwebtoken'); // 导入 jsonwebtoken 库
const { successRes, errorRes } = require('../../../utils/responseHandler');

const getList = async (req, res) => {
    try {
        //获取传进来的参数
        const params = req.query;
        const users = await userService.getAllUsersService(params);
        successRes(res, users);
    } catch (err) {
        errorRes(res, err.message);
    }
};

const getDetail = async (req, res) => {
    try {
        const userId = req.params.id;
        const user = await userService.getUserById(userId);
        successRes(res, user);
    } catch (err) {
        errorRes(res, err.message);
    }
};

const createOrUpdate = async (req, res) => {
    console.log(req.body);
    try {
        const userId = req.body.id;
        let user;
        if (userId) {
            // 更新用户
            user = await userService.updateUser(userId, req.body);
        } else {
            // 创建新用户
            user = await userService.addUser(req.body);
        }
        successRes(res, user);
    } catch (err) {
        errorRes(res, err.message);
    }
};

const deleteUser = async (req, res) => {
    try {
        const userId = req.params.id;
        await userService.deleteUserService(userId);
        successRes(res, { message: 'User deleted successfully' });
    } catch (err) {
        errorRes(res, err.message);
    }
};

module.exports = {
    getList,
    getDetail,
    createOrUpdate,
    deleteUser
};